package com.handong.handserialprogram.broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.handong.handserialprogram.model.status.EmergencyMsg;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SPUtil;

/**
 * Created by userKey on 2017/12/6.
 */

public class F1KeyCastReceiver extends BroadcastReceiver {

    private static final String TAG = F1KeyCastReceiver.class.getSimpleName();
    private byte mKeyCount = 0;
    private boolean mIsLongClick = false;

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        if (bundle.isEmpty()) {
            return;
        }
        int keyCode = intent.getIntExtra("keyCode", 0);
        boolean isKeyDown = intent.getBooleanExtra("keydown", false);
//        if (keyCode != 131) {
//            return;
//        }
        if (isKeyDown && !mIsLongClick) {
            if (mKeyCount <= 20) {
                mKeyCount++;
            } else {
                mIsLongClick = true;
            }
        }
        if (!isKeyDown) {
            if (isAllowEmergency(context)) {
                if (mIsLongClick) {
                    EventBusUtil.post(new EmergencyMsg(true));
                } else {
                    EventBusUtil.post(new EmergencyMsg(false));
                }
                mIsLongClick = false;
                mKeyCount = 0;
            }
        }
    }

    private boolean isAllowEmergency(Context context) {
        JLog.d(TAG, "   mIsLongClick |||  " + mIsLongClick);
        String id = SPUtil.getStringValue(SPUtil.MISSION_ID);
        if (TextUtils.isEmpty(id)) {
            AppUtil.showShortToast(context.getApplicationContext(), "任务未开始不能紧急报警");
            mIsLongClick = false;
            mKeyCount = 0;
            return false;
        }
        return true;
    }
}
